package com.android.manghe.zhuli.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.base.frame.extend.IRefresh
import com.android.base.frame.title.ETitleType
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.Glide.GlideHelper
import com.android.base.tools.StatusBarUtil
import com.android.base.tools.ToastUtil
import com.android.base.tools.permission.OnPermissionResultListener
import com.android.base.tools.permission.PermissionUtil
import com.android.manghe.R
import com.android.manghe.cache.UserHolder
import com.android.manghe.config.ConstantsUrl
import com.android.manghe.mine.activity.MyOrderActivity
import com.android.manghe.orderpay.model.ZhuLiRecordRes
import com.android.manghe.user.activity.LoginActivity
import com.android.manghe.view.RandomLayout
import com.android.manghe.zhuli.adapter.ZhuLiRecordAdapter
import com.android.manghe.zhuli.giftrain.RedPacketViewHelper
import com.android.manghe.zhuli.model.RedPackageBean
import com.android.manghe.zhuli.presenter.PZhuLiProgress
import com.githang.statusbar.StatusBarCompat
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_ping_dan_progress.*

class ZhuLiProgressActivity : MVPActivity<PZhuLiProgress>(), IRefresh, View.OnClickListener {

    companion object {
        fun showActivity(
            context: Context,
            orderSN: String,
            progress: Float,
            thumb: String,
            name: String
        ) {
            val intent = Intent(context, ZhuLiProgressActivity::class.java)
            intent.putExtra("orderSN", orderSN)
            intent.putExtra("progress", progress)
            intent.putExtra("thumb", thumb)
            intent.putExtra("name", name)
            context.startActivity(intent)
        }
    }

    var emptyView: View? = null
    var zhuLiAdapter: ZhuLiRecordAdapter? = null
    private var mShareAPI: UMShareAPI? = null
    var mRedPacketViewHelper: RedPacketViewHelper? = null

    private val shareListener = object : UMShareListener {
        /**
         * @descrption 分享成功的回调
         */
        override fun onResult(p0: SHARE_MEDIA?) {
            ToastUtil.showShort(this@ZhuLiProgressActivity, "分享成功")
        }

        /**
         * @descrption 分享取消的回调
         */
        override fun onCancel(p0: SHARE_MEDIA?) {
            ToastUtil.showShort(this@ZhuLiProgressActivity, "取消分享")
        }

        /**
         * @descrption 分享失败的回调
         */
        override fun onError(p0: SHARE_MEDIA?, p1: Throwable?) {
            ToastUtil.showShort(this@ZhuLiProgressActivity, "分享失败")
        }

        /**
         * @descrption 分享开始的回调
         */
        override fun onStart(p0: SHARE_MEDIA?) {
        }

    }


    override fun showToolBarType(): ETitleType {
        return ETitleType.NO_TITLE
    }

    override fun getLayoutId(): Int = R.layout.activity_ping_dan_progress
    override fun initData(savedInstanceState: Bundle?) {
        p.orderSN = intent.getStringExtra("orderSN")
        p.thumb = intent.getStringExtra("thumb")
        mShareAPI = UMShareAPI.get(this)
        mRedPacketViewHelper = RedPacketViewHelper(this)
        initView()
        initListener()

        if (UserHolder.getUserInfo(this) == null) {
            open(LoginActivity::class.java)
            ToastUtil.showLong(this, "请重新登录")
            finish()
            return
        }

        p.getZhuLiRecordList(true)
        p.getStrategy()
        p.getShareContent()
        p.getRedPackageList()
    }

    private fun initView() {
        StatusBarCompat.setTranslucent(window, true)
        val lp = RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        lp.topMargin = StatusBarUtil.getStatusBarHeight(this)
        layoutTopBar.layoutParams = lp
        GlideHelper.load(this, p.thumb, ivThumb)
        tvName.text = intent.getStringExtra("name")
        p.currentProgress = intent.getFloatExtra("progress", 0f)
        seekBar.progress = p.currentProgress.toInt()
        tvProgress.text = "已完成进度${p.currentProgress}%"
        checkMianDanComplete()

        recyclerView.layoutManager = LinearLayoutManager(this)
        zhuLiAdapter = ZhuLiRecordAdapter(this)
        recyclerView.adapter = zhuLiAdapter
    }

    private fun checkMianDanComplete() {
//        if (p.currentProgress >= 100f) {
//            //助力完成，弹出领取框
//            WinningDialog(
//                this,
//                tvName.text.toString(),
//                p.thumb,
//                object : WinningDialog.IWinningDialog {
//                    override fun clickGet() {
//                        p.confirmGet()
//                    }
//                }).show()
//        }
    }

    fun startFallDown() {
        mRedPacketViewHelper!!.launchGiftRainRocket(
            0,
            200,
            object : RedPacketViewHelper.GiftRainListener {
                override fun startLaunch() {}
                override fun startRain() {}
                override fun endRain() {}
                override fun openGift() {
                    if (p.redPackageList.isNotEmpty()) {
                        p.getRedPackage(p.redPackageList[0])
                        p.redPackageList.removeAt(0)
                        if (p.redPackageList.isEmpty()) {
                            mRedPacketViewHelper!!.endGiftRain()
                        }
                    }
                }

            })
    }

    fun updateProgress() {
        seekBar.progress = p.currentProgress.toInt()
        tvProgress.text = "已完成进度${p.currentProgress}%"
        checkMianDanComplete()
    }

    override fun onDestroy() {
        super.onDestroy()
        mRedPacketViewHelper?.endGiftRain()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initListener() {
        zhezhao.setOnTouchListener { _, _ ->
            true
        }
        ivBack.setOnClickListener {
            finish()
            MyOrderActivity.showActivity(this)
        }
        tvRule.setOnClickListener {
            //规则
            WebTextActivity.showActivity(
                this,
                "助力规则",
                ConstantsUrl.domain + ConstantsUrl.PinDanRule
            )
        }
        tvRecord.setOnClickListener {
            //助力记录
            switchTab(0)
        }
//        tvGongLue.setOnClickListener {
//            //助力攻略
//            switchTab(1)
//        }
        btnShare.setOnClickListener {
            layoutShare.visibility = View.VISIBLE
        }
        layoutShare.setOnClickListener {
            layoutShare.visibility = View.GONE
        }
        ivWechat.setOnClickListener(this)
        ivCircle.setOnClickListener(this)
        ivQQ.setOnClickListener(this)
        ivQZone.setOnClickListener(this)
    }

    private fun switchTab(i: Int) {
        tvRecord.setTextColor(Color.parseColor(if (i == 0) "#F84B03" else "#E3783D"))
        tvGongLue.setTextColor(Color.parseColor(if (i == 1) "#F84B03" else "#E3783D"))
        ivLeftTabIndic.visibility = if (i == 0) View.VISIBLE else View.GONE
        ivRightTabIndic.visibility = if (i == 1) View.VISIBLE else View.GONE
        refreshLayout.visibility = if (i == 0) View.VISIBLE else View.GONE
        tvGongLueContent.visibility = if (i == 1) View.VISIBLE else View.GONE
    }

    override fun onBackPressed() {
        if (layoutShare.visibility == View.VISIBLE) {
            layoutShare.visibility = View.GONE
        } else {
            super.onBackPressed()
            MyOrderActivity.showActivity(this)
        }
    }

    fun confirmGetGoodSuccess(){
        finish()
        MyOrderActivity.showActivity(this)
    }

    fun showZhuLiGongLue(desc: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            tvGongLueContent.text = Html.fromHtml(
                desc.replace("</p>", "").replace("\\r\\n", ""),
                Html.FROM_HTML_MODE_COMPACT
            )
        } else {
            tvGongLueContent.text = Html.fromHtml(desc.replace("</p>", "").replace("\\r\\n", ""))
        }
    }

    override fun onLoad() {
        p.getZhuLiRecordList(false)
    }

    override fun getRefreshView(): SmartRefreshLayout {
        return findViewById(R.id.refreshLayout)
    }

    override fun onRefresh() {
        p.getZhuLiRecordList(true)
    }

    fun update(recordList: List<ZhuLiRecordRes.DataBean.RecordInfo>) {
        zhuLiAdapter?.let {
            it.replaceData(recordList)
            if (recordList.isEmpty()) {
                emptyView = LayoutInflater.from(this).inflate(R.layout.no_data, null)
                emptyView!!.findViewById<TextView>(R.id.tvNoData).text = "暂无助力记录"
                it.emptyView = emptyView
            }
        }
    }

    fun updateRedPackage() {
        val leftPackage = arrayListOf<RedPackageBean>()
        val rightPackage = arrayListOf<RedPackageBean>()
        leftLayout.removeAllViews()
        rightLayout.removeAllViews()
        val leftRandomLayout = RandomLayout<RedPackageBean>(this)
        val rightRandomLayout = RandomLayout<RedPackageBean>(this)
        val lp = RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        leftRandomLayout.layoutParams = lp
        rightRandomLayout.layoutParams = lp
        p.redPackageList.forEachIndexed { index, redPackageBean ->
            val view = layoutInflater.inflate(R.layout.item_red_package, null, false)
            view.findViewById<TextView>(R.id.tvPercent).text = "+${redPackageBean.distance_amount}%"
            if (index % 2 == 0) {
                leftPackage.add(redPackageBean)
                leftRandomLayout.addViewAtRandomXY(view, redPackageBean)
                leftLayout.addView(leftRandomLayout)
                leftRandomLayout.setOnRandomItemClickListener { view, t ->
                    p.getRedPackage(t, leftRandomLayout, view)
                }
            } else {
                rightPackage.add(redPackageBean)
                rightRandomLayout.addViewAtRandomXY(view, redPackageBean)
                rightLayout.addView(rightRandomLayout)
                rightRandomLayout.setOnRandomItemClickListener { view, t ->
                    p.getRedPackage(t, rightRandomLayout, view)
                }
            }

        }
    }

    fun setCanLoadMore(canLoadMore: Boolean) {
        refreshLayout.isEnableLoadMore = canLoadMore
    }

    override fun onClick(v: View?) {
        PermissionUtil.requestPermissions(
            this, OnPermissionResultListener {
                val web = UMWeb(p.shareUrl)
                web.title = p.shareTitle//标题
                web.setThumb(UMImage(this@ZhuLiProgressActivity, p.thumb))  //缩略图
                web.description = p.shareContent//描述
                when (v) {
                    ivWechat -> {
                        if (mShareAPI!!.isInstall(this@ZhuLiProgressActivity, SHARE_MEDIA.WEIXIN)) {
                            layoutShare.visibility = View.GONE
                            ShareAction(this@ZhuLiProgressActivity)
                                .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                                .withMedia(web)
                                .setCallback(shareListener)//回调监听器
                                .share()
                        } else {
                            ToastUtil.showShort(this@ZhuLiProgressActivity, "请安装微信客户端")
                        }
                    }
                    ivCircle -> {
                        if (mShareAPI!!.isInstall(this@ZhuLiProgressActivity, SHARE_MEDIA.WEIXIN)) {
                            layoutShare.visibility = View.GONE
                            web.title = p.shareContent //标题
                            ShareAction(this@ZhuLiProgressActivity)
                                .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                                .withMedia(web)
                                .setCallback(shareListener)//回调监听器
                                .share()
                        } else {
                            ToastUtil.showShort(this@ZhuLiProgressActivity, "请安装微信客户端")
                        }
                    }
                    ivQQ -> {
                        if (mShareAPI!!.isInstall(this@ZhuLiProgressActivity, SHARE_MEDIA.QQ)) {
                            layoutShare.visibility = View.GONE
                            ShareAction(this@ZhuLiProgressActivity)
                                .setPlatform(SHARE_MEDIA.QQ)//传入平台
                                .withMedia(web)
                                .setCallback(shareListener)//回调监听器
                                .share()
                        } else {
                            ToastUtil.showShort(this@ZhuLiProgressActivity, "请安装QQ客户端")
                        }
                    }
                    ivQZone -> {
                        if (mShareAPI!!.isInstall(this@ZhuLiProgressActivity, SHARE_MEDIA.QQ)) {
                            layoutShare.visibility = View.GONE
                            ShareAction(this@ZhuLiProgressActivity)
                                .setPlatform(SHARE_MEDIA.QZONE)//传入平台
                                .withMedia(web)
                                .setCallback(shareListener)//回调监听器
                                .share()
                        } else {
                            ToastUtil.showShort(this@ZhuLiProgressActivity, "请安装QQ客户端")
                        }
                    }
                }
            },
            Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE,
            Permission.READ_PHONE_STATE
        )
    }
}